package cn.edu.scnu.interceptor;

import cn.edu.scnu.util.JwtUitl;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局的拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 全局拦截器
     * 后端接收到接口请求后，提供服务前，先执行preHandle，这个preHandle用来验证token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {

            Map<String, Object> claims = JwtUitl.parseToken(token);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            System.out.println(401);
            return false;
        }
    }
}
